import { Image } from 'expo-image';
import { useLocalSearchParams, useRouter } from 'expo-router';
import React, { useCallback, useEffect, useState } from 'react';
import {
    ActivityIndicator,
    Alert,
    ImageBackground,
    ScrollView,
    StatusBar,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import { Images } from '@/constants/images';
import { confirmReceive, getOrderDetail, OrderDetail, payOrder } from '@/services/mall';

export default function OrderDetailScreen() {
  const { tradeNo } = useLocalSearchParams<{ tradeNo: string }>();
  const router = useRouter();
  const insets = useSafeAreaInsets();

  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<OrderDetail | null>(null);

  const loadData = useCallback(async () => {
    if (!tradeNo) return;
    setLoading(true);
    try {
      const detail = await getOrderDetail(tradeNo);
      setData(detail);
    } catch (error) {
      console.error('加载订单详情失败:', error);
    }
    setLoading(false);
  }, [tradeNo]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // 去支付
  const handlePay = async () => {
    if (!data) return;
    try {
      const result = await payOrder(data.tradeNo, 'ALIPAY');
      if (result?.paySuccess) {
        Alert.alert('成功', '支付成功');
        loadData();
      }
    } catch (error) {
      console.error('支付失败:', error);
      Alert.alert('错误', '支付失败');
    }
  };

  // 确认收货
  const handleReceive = () => {
    Alert.alert('提示', '确认已收到商品？', [
      { text: '取消', style: 'cancel' },
      {
        text: '确认',
        onPress: async () => {
          try {
            await confirmReceive(tradeNo!);
            Alert.alert('成功', '确认收货成功');
            loadData();
          } catch (error) {
            console.error('确认收货失败:', error);
          }
        },
      },
    ]);
  };

  const goBack = () => {
    router.back();
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#fff" />
      </View>
    );
  }

  if (!data) {
    return (
      <View style={styles.loadingContainer}>
        <Text style={styles.errorText}>订单不存在</Text>
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <StatusBar barStyle="light-content" />
      <ImageBackground
        source={{ uri: Images.mine.kaixinMineBg }}
        style={styles.background}
        resizeMode="cover"
      >
        {/* 顶部导航 */}
        <View style={[styles.header, { paddingTop: insets.top }]}>
          <TouchableOpacity style={styles.backBtn} onPress={goBack}>
            <Text style={styles.backText}>←</Text>
          </TouchableOpacity>
          <Text style={styles.headerTitle}>订单详情</Text>
          <View style={styles.placeholder} />
        </View>

        <ScrollView style={styles.scrollView} showsVerticalScrollIndicator={false}>
          {/* 订单状态 */}
          <View style={styles.statusSection}>
            <Text style={styles.statusText}>{data.statusText}</Text>
          </View>

          {/* 收货地址 */}
          {data.address && (
            <ImageBackground
              source={{ uri: Images.common.itemBg }}
              style={styles.section}
              resizeMode="stretch"
            >
              <Text style={styles.sectionTitle}>收货信息</Text>
              <View style={styles.addressInfo}>
                <Text style={styles.addressName}>
                  {data.address.contactName} {data.address.contactNo}
                </Text>
                <Text style={styles.addressDetail}>
                  {data.address.province}{data.address.city}{data.address.district}{data.address.address}
                </Text>
              </View>
            </ImageBackground>
          )}

          {/* 商品信息 */}
          <ImageBackground
            source={{ uri: Images.common.itemBg }}
            style={styles.section}
            resizeMode="stretch"
          >
            <Text style={styles.sectionTitle}>商品信息</Text>
            <View style={styles.goodsItem}>
              <Image source={data.goodsCover} style={styles.goodsImage} contentFit="cover" />
              <View style={styles.goodsInfo}>
                <Text style={styles.goodsName} numberOfLines={2}>{data.goodsName}</Text>
                <View style={styles.goodsBottom}>
                  <Text style={styles.goodsPrice}>¥{data.paymentAmount}</Text>
                  <Text style={styles.goodsQty}>x{data.quantity}</Text>
                </View>
              </View>
            </View>
          </ImageBackground>

          {/* 订单信息 */}
          <ImageBackground
            source={{ uri: Images.common.itemBg }}
            style={styles.section}
            resizeMode="stretch"
          >
            <Text style={styles.sectionTitle}>订单信息</Text>
            <View style={styles.infoRow}>
              <Text style={styles.infoLabel}>订单编号</Text>
              <Text style={styles.infoValue}>{data.tradeNo}</Text>
            </View>
            <View style={styles.infoRow}>
              <Text style={styles.infoLabel}>下单时间</Text>
              <Text style={styles.infoValue}>{data.createTime}</Text>
            </View>
            <View style={styles.infoRow}>
              <Text style={styles.infoLabel}>实付金额</Text>
              <Text style={[styles.infoValue, styles.priceText]}>¥{data.paymentAmount}</Text>
            </View>
          </ImageBackground>

          <View style={{ height: 100 }} />
        </ScrollView>

        {/* 底部操作栏 */}
        {(data.status === 1 || data.status === 3) && (
          <View style={[styles.bottomBar, { paddingBottom: insets.bottom + 10 }]}>
            {data.status === 1 && (
              <TouchableOpacity style={styles.payBtn} onPress={handlePay} activeOpacity={0.8}>
                <ImageBackground
                  source={{ uri: Images.common.loginBtn }}
                  style={styles.payBtnBg}
                  resizeMode="stretch"
                >
                  <Text style={styles.payBtnText}>去支付</Text>
                </ImageBackground>
              </TouchableOpacity>
            )}
            {data.status === 3 && (
              <TouchableOpacity style={styles.payBtn} onPress={handleReceive} activeOpacity={0.8}>
                <ImageBackground
                  source={{ uri: Images.common.loginBtn }}
                  style={styles.payBtnBg}
                  resizeMode="stretch"
                >
                  <Text style={styles.payBtnText}>确认收货</Text>
                </ImageBackground>
              </TouchableOpacity>
            )}
          </View>
        )}
      </ImageBackground>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a2e',
  },
  background: {
    flex: 1,
  },
  loadingContainer: {
    flex: 1,
    backgroundColor: '#1a1a2e',
    justifyContent: 'center',
    alignItems: 'center',
  },
  errorText: {
    color: '#999',
    fontSize: 16,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 15,
    paddingBottom: 10,
  },
  backBtn: {
    width: 40,
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
  },
  backText: {
    color: '#fff',
    fontSize: 24,
  },
  headerTitle: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
  placeholder: {
    width: 40,
  },
  scrollView: {
    flex: 1,
  },
  statusSection: {
    backgroundColor: '#ff6b00',
    padding: 20,
    marginHorizontal: 15,
    borderRadius: 12,
    alignItems: 'center',
  },
  statusText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
  section: {
    marginTop: 10,
    marginHorizontal: 15,
    padding: 15,
    borderRadius: 12,
    overflow: 'hidden',
  },
  sectionTitle: {
    color: '#333',
    fontSize: 15,
    fontWeight: '600',
    marginBottom: 12,
  },
  addressInfo: {},
  addressName: {
    color: '#333',
    fontSize: 15,
    fontWeight: '500',
  },
  addressDetail: {
    color: '#666',
    fontSize: 13,
    marginTop: 6,
    lineHeight: 18,
  },
  goodsItem: {
    flexDirection: 'row',
  },
  goodsImage: {
    width: 80,
    height: 80,
    borderRadius: 8,
    backgroundColor: '#fff',
  },
  goodsInfo: {
    flex: 1,
    marginLeft: 12,
    justifyContent: 'space-between',
  },
  goodsName: {
    color: '#333',
    fontSize: 14,
    lineHeight: 20,
  },
  goodsBottom: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  goodsPrice: {
    color: '#ff6b00',
    fontSize: 16,
    fontWeight: '600',
  },
  goodsQty: {
    color: '#666',
    fontSize: 13,
  },
  infoRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingVertical: 8,
  },
  infoLabel: {
    color: '#666',
    fontSize: 13,
  },
  infoValue: {
    color: '#333',
    fontSize: 13,
  },
  priceText: {
    color: '#ff6b00',
    fontWeight: '600',
  },
  bottomBar: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    paddingHorizontal: 15,
    paddingTop: 10,
    backgroundColor: 'rgba(0,0,0,0.3)',
  },
  payBtn: {
    width: 120,
    height: 45,
    overflow: 'hidden',
  },
  payBtnBg: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  payBtnText: {
    color: '#fff',
    fontSize: 15,
    fontWeight: '600',
  },
});
